// me.js

import util from '../../utils/util.js'
import cache from '../../utils/cache.js'
let filter = require('../../utils/filter.js');
let api = require("../../requests/api.js");

let app = getApp()
Page(filter.identityFilter({

  /**
   * 页面的初始数据
   */
  data: {
    endUser: null,
    mobile: "添加手机号>",
    bindWechat: false,
    items: [{
        icon: '../../assets/res/icon_me_all_orders.png',
        text: '全部订单',
        path: '/pages/order/allOrders/allOrders?index=0'
      },
      {
        icon: '../../assets/res/icon_me_for_pay.png',
        text: '待付款',
        path: '/pages/order/allOrders/allOrders?index=1'
      },
      {
        icon: '../../assets/res/icon_me_send_goods.png',
        text: '待发货',
        path: '/pages/order/allOrders/allOrders?index=2',
      },
      {
        icon: '../../assets/res/icon_me_for_receive.png',
        text: '待收货',
        path: '/pages/order/allOrders/allOrders?index=3',
      },
    ],
    settings: [{
        icon: '../../assets/res/icon_me_for_giftCard.png',
        text: '礼品卡',
        path: '../giftCard/myGiftCard'
      },
      {
        icon: '../../assets/res/icon_me_coupons.png',
        text: '优惠券',
        path: '../preferential/coupon'
      },
      {
        icon: '../../assets/res/address.png',
        text: '收货地址',
        path: '../address/listAddress/address'
      },
      {
        icon: '../../assets/res/service_online.png',
        text: '联系客服',
        desc: '周一至周日 9:00 - 21：00',
        type: 'kefu',
      },
      {
        icon: '../../assets/res/icon_WeChat.png',
        text: '微信账号',
        desc: '去绑定',
        type: 'weixin'

      }
    ],
    loginCode: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    new app.WeToast();
    this.checkcode2Session((res) => {
      console.log('openId:' + res)
    })

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.requestUserInfo()

  },
  refreshUserInfo: function() {
    this.requestUserInfo()

  },

  //退出登录
  logoutClick: function() {
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定要退出登录？',
      showCancel: true,
      cancelText: "取消",
      cancelColor: "#333",
      confirmText: "确定",
      confirmColor: "#FFD444 ",
      success: function(res) {
        if (res.confirm) {
          that.requestLogout()
        }
      }
    })
  },

  // 退出登录
  requestLogout: function() {
    wx.showLoading({
      title: '',
    })
    api.post_logout(
      (data) => {
        wx.hideLoading()
        if (data.resCode == '0') {
          cache.endUser.sessionToken = ""
          cache.endUser = {}
          this.setData({
            endUser: cache.endUser,
            mobile: "",
            bindWechat: false
          })
          wx.removeStorageSync('openId')
          wx.removeStorageSync('endUser')
          wx.switchTab({
            url: '../../pages/home/home',
          })
        }
      },
      (error) => {
        wx.hideLoading()
        if (util.alertNetworkError(error)) {
          this.wetoast.toast({
            title: error.resMsg,
          })
        }
        console.log(error)
      },
      (data) => {
        wx.hideLoading()
      }
    )
  },

  // 用户信息
  requestUserInfo: function() {
    api.get_userInfo(
      (data) => {
        wx.hideNavigationBarLoading()
        if (data.resCode == '0') {
          data.data.sessionToken = cache.endUser.sessionToken
          wx.setStorage({
            key: 'endUser',
            data: data.data
          })
          cache.endUser = data.data
          //裁剪头像
          var res = wx.getSystemInfoSync()
          let pixelRatio = res.pixelRatio
          let windowWidth = res.windowWidth
          if (typeof cache.endUser.avatar == 'string') {
            let clipUrl = util.clipimage(cache.endUser.avatar + "", util.rpx2px(125))
            cache.endUser.avatar = clipUrl
          }
          if (cache.endUser.avatar == "" || cache.endUser.avatar == null) {
            cache.endUser.avatar = '../../assets/base_icon/defaultHead.png'
          }
          var userMobile = "添加手机号>"
          if (data.data.mobile != null && data.data.mobile != "") {
            userMobile = util.formatPhone(data.data.mobile);
          } else {
            userMobile = "添加手机号>"
          }
          //数据缓存判断,避免每次都请求用户数据
          this.setData({
            endUser: data.data,
            mobile: userMobile,
            bindWechat: data.data.bindWechat
          })
        }
      },
      (error) => {
        wx.hideNavigationBarLoading()
        console.log(error)
      },
      (data) => {
        wx.hideNavigationBarLoading()
      }
    )
  },

  bindGetUserInfo: function(e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      var userInfo = e.detail
      console.log(e.detail)
      that.checkcode2Session((res) => {
        console.log('openId:' + res)
        wx.getUserInfo({
          success: function(userData) {
            userInfo = userData
            userInfo.openId = res
            that.requestBindWechat(userInfo)
          }
        })

      })
    }
  },
  getPhoneNumber: function(e) {
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      var that = this;
      var userInfo = e.detail
      console.log(e.detail)
      this.checkcode2Session((res) => {
        console.log('openId:' + res)
        userInfo.openId = res
        that.requestBindMobile(userInfo)

      })
    }
  },
  // getLogin: function() {
  //   var that = this;
  //   if (that.data.mobile == '添加手机号>') {
  //     //调用登录接口
  //     wx.login({
  //       success: (ev) => {
  //         var code = ev.code
  //         that.setData({
  //           loginCode: code
  //         })
  //       }
  //     })
  //   }
  // },
  // getWechat: function() {
  //   console.log('绑定微信')
  //   var that = this;
  //   //调用登录接口
  //   wx.login({
  //     success: (ev) => {
  //       var code = ev.code
  //       console.log('获取login')
  //       that.setData({
  //         loginCode: code
  //       })
  //     }
  //   })
  // },
  //绑定手机号
  requestBindMobile: function(userInfo) {
    console.log('绑定手机号')
    var params = {
      openId: userInfo.openId,
      encryptedData: userInfo.encryptedData,
      iv: userInfo.iv
    };
    api.post_bindMobile(params,
      (data) => {
        if (data.resCode == '0') {
          wx.showToast({
            title: '手机号绑定成功',
            icon: 'none'
          })
          this.requestUserInfo()
        }
      },
      (error) => {
        if (util.alertNetworkError(error)) {
          this.wetoast.toast({
            title: error.resMsg,
          })
        }
        console.log(error)
      },
      (data) => {

      }
    )
  },
  //绑定微信
  requestBindWechat: function(userInfo) {
    wx.showLoading({
      title: '',
    })
    var params = {
      openId: userInfo.openId,
      encryptedData: userInfo.encryptedData,
      iv: userInfo.iv
    };
    api.post_bindWechat(params,
      (data) => {
        wx.hideLoading()
        if (data.resCode == '0') {
          wx.showToast({
            title: '微信绑定成功',
            icon: 'none'
          })
          this.requestUserInfo()
        }
      },
      (error) => {
        if (util.alertNetworkError(error)) {
          this.wetoast.toast({
            title: error.resMsg,
          })
        }
        console.log(error)
      },
      (data) => {
        wx.hideLoading()
      }
    )
  },
  checkcode2Session: function(successCallback) {
    var that = this;
    //检查是否登录过期
    wx.checkSession({
      success: function(res) {
        console.log('我的界面，登录未过期')
        //进入页面先取缓存
        wx.getStorage({
          key: 'openId',
          success: function(res) {
            console.log('取出缓存openId' + res.data)
            that.setData({
              loginCode: res.data
            })
            util.isFunction(successCallback) && successCallback(res.data);
          },
          fail: function(res) {
            console.log('s:获取失败')
            //冲洗获取openId
            wx.login({
              success: (ev) => {
                var code = ev.code
                that.code2Session(code, (res) => {
                  that.setData({
                    loginCode: res
                  })
                  util.isFunction(successCallback) && successCallback(res);
                })
              }
            })
          }
        })
      },
      fail: function(res) {
        console.log('我的界面，登录已过期，重新取code')
        wx.login({
          success: (ev) => {
            var code = ev.code
            that.code2Session(code, (res) => {
              util.isFunction(successCallback) && successCallback(res);
            })
          }
        })
      }
    })
  },
  code2Session: function(code, successCallback) {
    var params = {
      code: code
    }
    api.post_code2Session(params, (res) => {
      console.log(res)
      if (res.data) {
        wx.setStorage({
          key: 'openId',
          data: res.data.openId
        })
        util.isFunction(successCallback) && successCallback(res.data.openId);
      }
    }, (data) => {
      if (util.alertNetworkError(data)) {
        this.wetoast.toast({
          title: data.resMsg,
        })
      }

    }, () => {

    });
  },

}))